package com.ash.socketb.dual.length;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 这个是一个双向通信的例子，典型的request-response机制
 * <p>
 * https://www.cnblogs.com/yiwangzhibujian/p/7107785.html#q1
 * <p>
 * 如何告知对方已发送完命令
 * 通过Socket关闭
 * 通过Socket关闭输出流的方式
 * 通过约定符号
 * 通过指定长度
 */
public class ClientDualDemo {

    public static void main(String[] args) throws IOException {


        System.out.println(sendReq("localhost", 8081, "asdf12asdfasdf"));


    }

    /**
     * 这里演示前两个字节固定为长度
     *
     * @param host
     * @param port
     * @param requestBody
     * @return
     * @throws IOException
     */
    private static String sendReq(String host, int port, String requestBody) throws IOException {
        try (
                Socket socket = new Socket(host, port);
                OutputStream outputStream = socket.getOutputStream();
                InputStream inputStream = socket.getInputStream();
        ) {
            int contentLength = requestBody.length();
            outputStream.write(contentLength >> 8);
            outputStream.write(contentLength);
            outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));


            String responseText = readResponse(inputStream);

            outputStream.write(contentLength >> 8);
            outputStream.write(contentLength);
            outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));

            responseText = responseText + "\n" + readResponse(inputStream);

            return responseText;
        }
    }

    private static String readResponse(InputStream inputStream) throws IOException {
        int first = inputStream.read();
        if (first == -1) {
            System.out.println("关闭流了");
            return null;
        }

        int second = inputStream.read();

        int len = (first << 8) + second;
        byte[] buff = new byte[len];
        int read = inputStream.read(buff);

        // 获取响应内容
        String responseText = new String(buff, 0, read, StandardCharsets.UTF_8);
        return responseText;
    }
}
